/*
 * BackupEngine.java
 *
 * Created on Oct 12, 2007, 8:36:09 PM
 *
 * Copyright (c) October 14, 2007 by Dean Del Ponte
 * http://www.sourceseed.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by  the Free Software Foundation; either version 3 of the License or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this program; see the file COPYING.TXT.  If not, write to
 * the Free Software Foundation Inc., 59 Temple Place - Suite 330,
 * Boston, MA  02111-1307 USA
 */

package org.sourceseed.tools.backup.backThatThingUp;

import java.util.ArrayList;
import java.util.List;
import org.sourceseed.tools.backup.tasks.BackupProjectSchedulerTask;
import org.tiling.scheduling.ScheduleIterator;
import org.tiling.scheduling.Scheduler;
import org.tiling.scheduling.iterators.CompositeIterator;
import org.tiling.scheduling.iterators.RestrictedDailyIterator;

/**
 * Initiates the scheduling of backups
 *
 * @author Dean Del Ponte
 */
public class BackupEngine implements IBackupEngine {

    private final Scheduler scheduler = new Scheduler();

    public BackupEngine() {
    }

    public void schedule(List<Project> projects, BackupConfig backupConfig) {
        for (Project project : projects) {
            project.setMailServer(backupConfig.getMailServer());
            ScheduleIterator i = new CompositeIterator(getScheduleIterators(project));            
            scheduler.schedule(new BackupProjectSchedulerTask(project) , i);
        }
    }

    public void cancel() {
        scheduler.cancel();
    }

    private ScheduleIterator[] getScheduleIterators(Project project) {
        List<DayTimes> dayTimes = project.getSchedule();
        List<RestrictedDailyIterator> scheduleIterators = new ArrayList<RestrictedDailyIterator>();

        for (DayTimes dt : dayTimes) {
            for (SimpleTime time : dt.getTimes()) {
                scheduleIterators.add(new RestrictedDailyIterator(time.getHour(), time.getMinute(), time.getSecond(), dt.getDay()));
            }
        }

        RestrictedDailyIterator[] rdi = new RestrictedDailyIterator[scheduleIterators.size()];

        int i = 0;
        for (RestrictedDailyIterator it : scheduleIterators) {
            rdi[i] = it;
            i++;
        }

        return rdi;
    }
}